package org.oschina.api.manage.plugin.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.upload.UploadConfigType;
import org.oschina.api.upload.service.UploadService;
import org.oschina.bean.Result;
import org.oschina.helper.topic.ITopicHelper;
import org.oschina.plugin.PluginHelper;
import org.oschina.plugin.bean.PluginBean;
import org.oschina.plugin.bean.PluginCreateSyncBean;
import org.oschina.plugin.bean.PluginRemoveSyncBean;
import org.oschina.plugin.bean.PluginStatusSyncBean;
import org.oschina.security.annotation.Require;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class PluginService extends BaseService {

	private final static Logger logger=LoggerFactory.getLogger(PluginService.class);
	
	@Autowired
	private PluginHelper pluginHelper;
	@Autowired
	private UploadService uploadService;
	@Autowired
	private ITopicHelper topicHelper;
	
	/**
	 * 获得所有插件
	 * @return
	 */
	@Require(authorization=Module.MODULE_14)
	public List<PluginBean> get()
	{
		return pluginHelper.getPlugins();
	}
	
	/**
	 * 设置激活
	 * @param id
	 * @param enabled
	 * @return
	 */
	@Require(authorization=Module.MODULE_14)
	public Result setEnabled(int id,boolean enabled)
	{
		topicHelper.send(Constants.TOPIC_PLUGIN_REMOVE_SYNC, new PluginStatusSyncBean(id,enabled));
		return ResultUtil.getSuccess(Message.UPDATE_SUCCESS_DELAY);
	}
	
	/**
	 * 移除插件
	 * @param id
	 * @return
	 */
	@Require(authorization=Module.MODULE_14)
	public Result remove(int id)
	{
		topicHelper.send(Constants.TOPIC_PLUGIN_REMOVE_SYNC, new PluginRemoveSyncBean(id));
		return ResultUtil.getSuccess(Message.DELETE_SUCCESS_DELAY);
	}
	
	/**
	 * 添加插件
	 * @param file
	 * @return
	 */
	@Require(authorization=Module.MODULE_14)
	public Result add(File file)
	{
		Result result=uploadService._baseUpload(UploadConfigType.PLUGIN, false, false, file);
		if(!result.isSuccess())
			return result;
		
		try
		{
			topicHelper.send(Constants.TOPIC_PLUGIN_CREATE_SYNC, new PluginCreateSyncBean(file.getName(),FileUtils.readFileToByteArray(file)));
			return ResultUtil.getSuccess(Message.CREATE_SUCCESS_DELAY);
		}
		catch (IOException e)
		{
			logger.error("添加插件错误 - ",e);
			return ResultUtil.getSuccess(Message.ERROR_APP_ERROR);
		}
	}
}